Dictionary Class

An object that contains a list of key-value pairs. Both keys and values are Variants.

Events

None

Properties

BinCount

Count

Value


Methods

Clear

HasKey

Key

Keys

Lookup

Remove

Values


More information available in parent classes: Object


Notes

The Dictionary class provides the functionality of the Collection class and offers several advantages: With the Collection class, the time taken to locate an item is a function of the number of items in the Collection because the search is sequential. A Dictionary uses a hash table, making the time (relatively) independent of the number of items. It is designed for high-speed lookups. Also, the key parameter in a Dictionary is a Variant, but is a String in the Collection class, giving you greater flexibility. On the other hand, the Collection can store multiple values per key. When you assign a value to a key that is already in the Dictionary, the new value replaces the old one.


Example

The following example takes advantage of the fact that the key is a Variant, and not necessarily a number. In this example, the keys are colors and the values are descriptions.

Dim d as New Dictionary
d.Value( RGB(255,0,0))="This is pure red."
d.Value( RGB(0,255,255))="This is pure cyan."
MsgBox d.value(d.Key(1)) //retrieves cyan
Exception err as RuntimeException
 If err IsA KeyNotFoundException then
   MsgBox "Key not in the dictionary"
 End if
 If err IsA OutOfBoundsException then
   MsgBox "The index of the key is out of bounds!"
 End if

If the index passed to the Key method in the line:

MsgBox d.value(d.Key(1))

is not an element in the dictionary, an OutOfBoundsException occurs and the Exception block at the end of the method will trap it. You could also retrieve this value in the dictionary by passing the Value method the key rather than the key's index

MsgBox dict.value( RGB(0,255,255))

:

In this case, if you pass a key that is not in the dictionary, a KeyNotFoundException will occur and the Exception block will also trap it and display the appropriate error message.

Instead of the Exception block, you could first use the HasKey method before trying to access the value:

If d.HasKey( RGB(0,255,255)) then
  MsgBox d.value( RGB(0,255,255))
Else
  MsgBox "Key not in the dictionary!"
End If

See Also

KeyNotFoundException error; Collection, Variant classes.